<template>
  <div class="performance-result">
    <!-- 顶部卡片统计信息 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon success">
                <el-icon><CircleCheckFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon running">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.running }}</div>
                <div class="stat-label">执行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon failed">
                <el-icon><CircleCloseFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.failed }}</div>
                <div class="stat-label">失败</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total }}</div>
                <div class="stat-label">总报告</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="search.dataTime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTimeOptions"
            :shortcuts="shortcuts"
            range-separator="至"
            :clearable="false"
            class="date-picker"
          />
        </el-form-item>
        <el-form-item label="任务名称">
          <el-input v-model="search.taskName" placeholder="请输入任务名称" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="报告状态">
          <el-select style="width: 120px" v-model="search.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="已完成" value="0" />
            <el-option label="执行中" value="1" />
            <el-option label="运行失败" value="99" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="clickSearch" plain>
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="clearSearch" plain>
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="action-toolbar">
      <div class="left-actions">
        <el-button type="primary" @click="taskDiff" plain>
          <el-icon><DataAnalysis /></el-icon>任务对比
        </el-button>
      </div>
      <div class="right-actions">
        <el-button circle @click="refreshData">
          <el-icon><RefreshRight /></el-icon>
        </el-button>
        <el-button circle>
          <el-icon><Setting /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table
        ref="table"
        highlight-current-row
        :data="reportList"
        style="width: 100%"
        size="default"
        :border="false"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
        table-layout="auto"
        v-loading="tableLoading"
        height="500"
      >
        <el-table-column label="报告名称" prop="reportName" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="report-name-cell">
              <el-icon v-if="scope.row.status === '报告-已完成'" class="status-icon success"><CircleCheckFilled /></el-icon>
              <el-icon v-else-if="scope.row.status === '报告-运行失败'" class="status-icon failed"><CircleCloseFilled /></el-icon>
              <el-icon v-else-if="scope.row.status === '报告-执行中'" class="status-icon running"><Loading /></el-icon>
              <span>{{ scope.row.reportName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="reportStatus" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.reportStatus === '0'" type="success" effect="light" size="small">
              <el-icon><CircleCheckFilled /></el-icon> 已完成
            </el-tag>
            <el-tag v-else-if="scope.row.reportStatus === '99'" type="danger" effect="light" size="small">
              <el-icon><CircleCloseFilled /></el-icon> 运行失败
            </el-tag>
            <el-tag v-else-if="scope.row.reportStatus === '1'" type="primary" effect="light" size="small">
              <span class="running-tag">
                <el-icon class="is-loading"><Loading /></el-icon>
                执行中
              </span>
            </el-tag>
            <el-tag v-else type="info" effect="light" size="small">
              {{ getStatusText(scope.row.reportStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="任务名称" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.task?.taskName || scope.row.taskName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="任务模式" width="100" align="center">
          <template #default="scope">
            {{ getTaskTypeText(scope.row.task?.taskType || scope.row.taskType) }}
          </template>
        </el-table-column>
        <el-table-column label="压测模式" width="120" align="center">
          <template #default="scope">
            {{ scope.row.pressureMode || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="测试环境" width="120" align="center">
          <template #default="scope">
            {{ scope.row.envName }}
          </template>
        </el-table-column>
        <el-table-column label="总请求数" width="120" align="center">
          <template #default="scope">
            {{ formatNumber(scope.row.totalRequests) }}
          </template>
        </el-table-column>
        <el-table-column label="成功率" width="100" align="center">
          <template #default="scope">
            <span :class="getSuccessRateClass(getSuccessRate(scope.row))">
              {{ getSuccessRate(scope.row) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="平均响应时间" width="130" align="center">
          <template #default="scope">
            {{ formatResponseTime(scope.row.avgResponseTime) }}
          </template>
        </el-table-column>

        <!-- 性能指标区域 - 带小图表 -->
        <el-table-column label="平均RPS" width="120" align="center">
          <template #default="scope">
            <div class="metric-cell">
              <span class="metric-value">{{ scope.row.avgTps || '-' }}</span>
              <!-- 添加TPS迷你条形图 -->
              <div v-if="scope.row.avgTps" class="mini-bar-chart">
                <div class="mini-bar" :style="{ width: `${Math.min(Number(scope.row.avgTps)/2, 100)}%` }"></div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="运行完成时CPU" width="120" align="center">
          <template #default="scope">
            <div class="metric-cell">
              <span class="metric-value">{{ formatPercentage(scope.row.avgCpu) }}</span>
              <el-progress
                v-if="scope.row.avgCpu"
                :percentage="Number(scope.row.avgCpu)"
                :color="getCpuColor(scope.row.avgCpu)"
                :stroke-width="4"
                :show-text="false"
              ></el-progress>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="运行完成时内存" width="120" align="center">
          <template #default="scope">
            <div class="metric-cell">
              <span class="metric-value">{{ formatPercentage(scope.row.avgMemory) }}</span>
              <el-progress
                v-if="scope.row.avgMemory"
                :percentage="Number(scope.row.avgMemory)"
                :color="getMemoryColor(scope.row.avgMemory)"
                :stroke-width="4"
                :show-text="false"
              ></el-progress>
            </div>
          </template>
        </el-table-column>

        <!-- 时间信息 -->
        <el-table-column label="执行时间" min-width="300" align="center">
          <template #default="scope">
            <div class="time-info">
              <el-tooltip :content="$tools.rTime(scope.row.startTime || scope.row.start_time)" placement="top">
                <div class="time-item"><el-icon><Calendar /></el-icon> {{ formatDate(scope.row.startTime || scope.row.start_time) }}</div>
              </el-tooltip>
              <div class="time-separator">至</div>
              <el-tooltip :content="$tools.rTime(scope.row.endTime || scope.row.end_time)" placement="top">
                <div class="time-item"><el-icon><Calendar /></el-icon> {{ formatDate(scope.row.endTime || scope.row.end_time) }}</div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="执行人" prop="executor" width="100" align="center">
          <template #default="scope">
            <el-avatar :size="24" :src="getAvatarUrl(scope.row.executor || scope.row.creator)">{{ getInitials(scope.row.executor || scope.row.creator) }}</el-avatar>
            <span class="executor-name">{{ scope.row.executor || scope.row.creator || '未知' }}</span>
          </template>
        </el-table-column>

        <!-- 操作按钮 -->
        <el-table-column label="操作" width="190" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="success" size="small" plain @click="clickView(scope.row)">
                <el-icon><View /></el-icon>查看
              </el-button>
              <el-button type="primary" size="small" plain @click="exportReport(scope.row)">
                <el-icon><Download /></el-icon>导出
              </el-button>
              <el-dropdown trigger="click">
                <el-button style="margin-left: 10px" type="info" size="small" plain>
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="delPresetting(scope.row.id)" style="color: var(--el-color-danger)">
                      <el-icon><Delete /></el-icon>删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="currentPages"
          @size-change="handleSizeChange"
          :page-sizes="[20, 50, 100, 200]"
          :default-page-size="20"
          :total="pages.count"
          :current-page="pages.current"
          :hide-on-single-page="false"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>

  <!-- 任务对比对话框已移除，改用独立页面 -->
</template>

<script>
import { ElMessage } from "element-plus";
import {mapState} from "vuex";
import environmentMixin from '@/mixins/environmentMixin';
import {
  Refresh, Search, DataAnalysis, View, Download, Delete,
  RefreshRight, Setting, FullScreen, Plus, Calendar, Timer,
  CircleCheckFilled, CircleCloseFilled, Loading, DocumentCopy,
  EditPen, ArrowDown, TrendCharts, PieChart, InfoFilled
} from '@element-plus/icons-vue';

export default {
  mixins: [environmentMixin],
  components: {
    Refresh, Search, DataAnalysis, View, Download, Delete,
    RefreshRight, Setting, FullScreen, Plus, Calendar,
    CircleCheckFilled, CircleCloseFilled, Loading, DocumentCopy,
    EditPen, ArrowDown, TrendCharts, PieChart, InfoFilled
  },
  data() {
    return {
      pages: {
        current: 1,
        count: 0,
        pageSize: 20
      },
      tableLoading: false,
      reportList: [],
      selectionConfig: {
        selectedRowKeys: [],
        selectionChange: this.handleSelectionChange
      },
      search:{
        taskName: '',
        status: '',
        dataTime: [this.getFormattedDate(new Date(new Date().getTime() - 6 * 24 * 60 * 60 * 1000)),
                  this.getFormattedDate(new Date(), true)],
      },
      defaultTimeOptions: ['0000-01-01 00:00:00', '0000-01-01 23:59:59'],
      shortcuts: [
        {
          text: '今天',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        },
        {
          text: '近三天',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setDate(end.getDate() - 2);
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        },
        {
          text: '近七天',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setDate(end.getDate() - 6);
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        },
       {
          text: '近一个月',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setMonth(end.getMonth() - 1);
            start.setHours(0, 0, 0); // 设置时分秒为 00:00:00
            end.setHours(23, 59, 59); // 设置时分秒为 23:59:59
            return [start, end];
          })
        }],
      // 统计数据
      statistics: {
        total: 0,
        completed: 0,
        running: 0,
        failed: 0
      },

      // 对话框数据已移除，使用独立的任务对比页面
    }
  },
  mounted() {
    this.initTableData();
  },
  computed: {
    ...mapState({
      pro: state => state.pro
    })
  },
  methods: {
    // 表格行样式
    tableRowClassName({ row }) {
      if (row.status === '报告-执行中') {
        return 'running-row';
      }
      return '';
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pages.pageSize = size;
      this.getTableData();
    },

    // 刷新数据
    refreshData() {
      this.tableLoading = true;
      setTimeout(() => {
        this.tableLoading = false;
        ElMessage({
          type: 'success',
          message: '数据已刷新',
          duration: 1500
        });
      }, 800);
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },

    // 获取CPU颜色
    getCpuColor(value) {
      const num = Number(value);
      if (num < 60) return '#67C23A';
      if (num < 80) return '#E6A23C';
      return '#F56C6C';
    },

    // 获取内存颜色
    getMemoryColor(value) {
      const num = Number(value);
      if (num < 50) return '#67C23A';
      if (num < 75) return '#E6A23C';
      return '#F56C6C';
    },

    // 获取用户头像
    getAvatarUrl(username) {
      // 实际项目中可以根据用户名从后端获取头像
      return '';
    },

    // 获取用户名首字母
    getInitials(username) {
      if (!username) return '';
      return username.charAt(0).toUpperCase();
    },

    // 初始化表格数据和小图表
    initTableData() {
      this.loadStatistics();
      this.getTableData();
    },

    // 获取表格数据
    async getTableData() {
      this.tableLoading = true;
      try {
        const params = {
          project_id: this.pro.id,
          page: this.pages.current,
          page_size: this.pages.pageSize
        };

        // 添加搜索条件
        if (this.search.taskName) {
          params.taskName = this.search.taskName;
        }
        if (this.search.status) {
          params.reportStatus = this.search.status.replace('报告-', '');
        }
        if (this.search.dataTime && this.search.dataTime.length === 2) {
          params.start_time = this.search.dataTime[0];
          params.end_time = this.search.dataTime[1];
        }

        const response = await this.$api.getTaskReports(params);

        if (response.status === 200) {
          let reportList = response.data.result || response.data.data || [];

          // 数据处理：确保字段映射正确
          reportList = reportList.map(item => ({
            ...item,
            // 确保状态字段正确映射
            reportStatus: item.reportStatus || item.status,
            // 确保任务信息正确映射 - 重要：保留原始的task对象
            taskName: item.taskName || item.task?.taskName || item.name,
            taskType: item.taskType || item.task?.taskType,
            pressureMode: item.pressureMode || item.task?.pressureMode,
            // 确保任务ID正确映射
            taskId: item.taskId || item.task?.id || item.task_id,
            // 确保环境信息正确映射
            envName: item.envName,
            // 确保执行人信息正确映射
            executor: item.executor || item.creator || item.user?.username,
            // 确保时间字段正确映射
            startTime: item.startTime || item.start_time || item.createTime,
            endTime: item.endTime || item.end_time || item.updateTime,
            // 确保性能指标正确映射且保留小数
            avgCpu: item.avgCpu ? Number(item.avgCpu).toFixed(2) : null,
            avgMemory: item.avgMemory ? Number(item.avgMemory).toFixed(2) : null,
            avgResponseTime: item.avgResponseTime ? Number(item.avgResponseTime) : null,
            avgTps: item.avgTps ? Number(item.avgTps).toFixed(2) : null,
            totalRequests: item.totalRequests ? Number(item.totalRequests) : null,
            successRequests: item.successRequests ? Number(item.successRequests) : null,
            failedRequests: item.failedRequests ? Number(item.failedRequests) : null
          }));

          this.reportList = reportList;
          this.pages.count = response.data.count || response.data.total || 0;
          this.pages.current = response.data.current || response.data.page || 1;
        }
      } catch (error) {
        console.error('获取报告列表失败:', error);
        ElMessage({
          type: 'error',
          message: '获取报告列表失败: ' + (error.response?.data?.message || error.message || '未知错误'),
          duration: 3000
        });
      } finally {
        this.tableLoading = false;
      }
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        const params = {
          project_id: this.pro.id
        };

        const response = await this.$api.getTaskReport(params);

        if (response.status === 200) {
          this.statistics = response.data;
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
      }
    },

    handleSelectionChange(selected) {
      this.selectionConfig.selectedRowKeys = selected.map(item => item.id);
    },

    currentPages(currentPage) {
      this.pages.current = currentPage;
      this.getTableData();
    },

    convertToTimeZoneFormat(dateStr, timeZone) {
      const moment = require('moment-timezone');
      const m = moment.tz(dateStr, timeZone);
      return m.format('YYYY-MM-DD HH:mm:ss'); // 格式化为年月日时分秒
    },

    getFormattedDate(date, endOfDay = false) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      let hours, minutes, seconds;

      if (endOfDay) {
        hours = '23';
        minutes = '59';
        seconds = '59';
      } else {
        hours = '00';
        minutes = '00';
        seconds = '00';
      }

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    clearSearch() {
      this.search = {
        taskName: '',
        status: '',
        dataTime: [this.getFormattedDate(new Date(new Date().getTime() - 6 * 24 * 60 * 60 * 1000)),
                      this.getFormattedDate(new Date(), true)]
      };
      this.pages.current = 1;
      this.getTableData();
    },

    clickSearch() {
      this.pages.current = 1;
      this.getTableData();
    },

    clickView(row) {
      if (!row || !row.id) {
        this.$message.error('报告ID不能为空')
        return
      }
      this.$router.push({
        name: 'PerformanceResult-Detail',
        params: { id: row.id }
      });
    },

    taskDiff() {
      // 跳转到专门的任务对比页面
      this.$router.push('/performance/comparison')
    },

    // 对比相关方法已移除，使用独立页面

    // 对比HTML构建方法已移除，使用独立页面

    // 通用格式化方法保留

    // 格式化指标值
    formatMetricValue(metric, value) {
      if (!value && value !== 0) return '-';

      switch (metric) {
        case 'avgResponseTime':
          return value < 1000 ? `${value}ms` : `${(value/1000).toFixed(2)}s`;
        case 'successRate':
        case 'avgCpu':
        case 'avgMemory':
          return `${Number(value).toFixed(1)}%`;
        case 'totalRequests':
          return Number(value).toLocaleString();
        default:
          return Number(value).toFixed(1);
      }
    },

    // 获取指标颜色
    getMetricColor(metric, value) {
      switch (metric) {
        case 'avgResponseTime':
          return value > 1000 ? '#f56c6c' : value > 500 ? '#e6a23c' : '#67c23a';
        case 'avgTps':
          return value > 100 ? '#67c23a' : value > 50 ? '#e6a23c' : '#f56c6c';
        case 'successRate':
          return value > 95 ? '#67c23a' : value > 80 ? '#e6a23c' : '#f56c6c';
        default:
          return '#409eff';
      }
    },

    // 对比专用方法已删除

    async exportReport(row) {
      try {
        if (!row || !row.id) {
          ElMessage({
            type: 'error',
            message: '导出失败: 报告ID不能为空',
            duration: 3000
          });
          return;
        }

        ElMessage({
          type: 'info',
          message: '报告导出中，请稍候...',
          duration: 2000
        });

        const response = await this.$api.exportSingleReport(row.id);

        if (response.status === 200) {
          const contentDisposition = response.headers['content-disposition'];
          let filename = '性能测试报告.xlsx';
          
          // 尝试从header获取文件名
          if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename="?([^"]*)"?/);
            if (filenameMatch && filenameMatch[1]) {
              filename = filenameMatch[1];
            }
          } else {
            // 使用报告名称作为文件名
            filename = `${row.reportName || '性能测试报告'}.xlsx`;
          }

          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = filename;
          link.click();

          ElMessage({
            type: 'success',
            message: '导出成功',
            duration: 2000
          });
        }
      } catch (error) {
        ElMessage({
          type: 'error',
          message: '导出失败: ' + (error.message || '未知错误'),
          duration: 3000
        });
      }
    },

    async delPresetting(id) {
      try {
        const response = await this.$api.delTaskReport(id);

        if (response.status === 204) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          });
          this.getTableData();
          this.loadStatistics();
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage({
            type: 'error',
            message: '删除失败: ' + (error.message || '未知错误')
          });
        }
      }
    },

    // 格式化百分比（保留两位小数）
    formatPercentage(value) {
      if (!value && value !== 0) return '-';
      const num = Number(value);
      return num.toFixed(2) + '%';
    },

    // 格式化数字
    formatNumber(num) {
      if (!num && num !== 0) return '-';
      return num.toLocaleString();
    },

    // 获取成功率样式
    getSuccessRateClass(rate) {
      const num = Number(rate);
      if (num >= 95) return 'success-rate-high';
      if (num >= 80) return 'success-rate-medium';
      return 'success-rate-low';
    },

    // 获取成功率
    getSuccessRate(row) {
      if (!row.totalRequests || row.totalRequests === 0) return 0;
      const successCount = row.totalRequests - (row.failedRequests || 0);
      const rate = (successCount / row.totalRequests) * 100;
      return rate.toFixed(1);
    },

    // 格式化响应时间
    formatResponseTime(time) {
      if (!time) return '-';
      const num = Number(time);
      if (num < 1000) return num.toFixed(0) + 'ms';
      return (num / 1000).toFixed(2) + 's';
    },

    // 格式化持续时间
    formatDuration(duration) {
      if (!duration) return '-';
      const seconds = Math.floor(duration / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);

      if (hours > 0) {
        return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
      } else if (minutes > 0) {
        return `${minutes}m ${seconds % 60}s`;
      } else {
        return `${seconds}s`;
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '0': '已完成',
        '1': '执行中',
        '99': '运行失败'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取任务类型文本
    getTaskTypeText(type) {
      if (!type && type !== 0) return '-';
      const typeMap = {
        '1': '普通任务',
        '2': '定时任务',
        '10': '普通任务',
        '20': '定时任务'
      };
      return typeMap[String(type)] || '-';
    },

    // 获取运行模式文本
    getRunPatternText(pattern) {
      if (!pattern && pattern !== 0) return '-';
      const patternMap = {
        '1': '并发模式',
        '2': '阶梯模式',
        '10': '并发模式',
        '20': '阶梯模式'
      };
      return patternMap[String(pattern)] || '-';
    },

    // 对话框相关方法

    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        '0': 'success',
        '1': 'primary',
        '99': 'danger'
      };
      return typeMap[status] || 'info';
    },

    // 获取对比表格数据
    getComparisonTableData() {
      if (!this.comparisonDialogData.comparisonData?.tasks) return [];

      const tasks = this.comparisonDialogData.comparisonData.tasks;
      const metrics = ['avgResponseTime', 'avgTps', 'successRate', 'avgCpu', 'avgMemory', 'totalRequests'];
      const metricLabels = {
        avgResponseTime: '平均响应时间(ms)',
        avgTps: '平均TPS',
        successRate: '成功率(%)',
        avgCpu: '平均CPU(%)',
        avgMemory: '平均内存(%)',
        totalRequests: '总请求数'
      };

      return metrics.map(metric => {
        const values = tasks.map(task => task[metric] || 0);
        const bestIndex = this.getBestMetricIndex(metric, values);

        return {
          metric: metricLabels[metric],
          values: values.map(value => this.formatMetricValue(metric, value)),
          bestIndex,
          bestValue: this.formatMetricValue(metric, values[bestIndex])
        };
      });
    },

    // 获取指标百分比
    getMetricPercentage(metric, value) {
      if (!this.comparisonDialogData.comparisonData?.tasks) return 0;

      const tasks = this.comparisonDialogData.comparisonData.tasks;
      const values = tasks.map(task => task[metric] || 0);
      const maxValue = Math.max(...values.filter(v => v > 0));

      if (maxValue === 0) return 0;
      return Math.min((value / maxValue) * 100, 100);
    },

    // 获取最佳任务
    getBestTask() {
      if (!this.comparisonDialogData.comparisonData?.tasks) return {};

      const tasks = this.comparisonDialogData.comparisonData.tasks;
      return this.findBestPerformanceTask(tasks);
    },
  },

  created() {

  }
}
</script>

<style scoped>
.performance-result {
  padding: 16px;
  background-color: var(--el-bg-color-page, #f2f3f5);
  min-height: calc(100vh - 100px);
}

/* 统计卡片样式 */
.statistics-cards {
  margin-bottom: 16px;
}

.stat-card {
  transition: all 0.3s;
  cursor: pointer;
  border-radius: 8px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 16px;
}

.stat-icon.success {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.stat-icon.running {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.stat-icon.failed {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.stat-icon.total {
  background-color: rgba(121, 187, 255, 0.1);
  color: #79BBFF;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  line-height: 1.2;
  color: var(--el-text-color-primary);
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

/* 搜索区域样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.date-picker {
  width: 340px;
}

/* 操作工具栏 */
.action-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

/* 表格样式 */
.table-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.running-row {
  background-color: rgba(64, 158, 255, 0.05);
}

.report-name-cell {
  display: flex;
  align-items: center;
}

.status-icon {
  margin-right: 8px;
  font-size: 16px;
}

.status-icon.success {
  color: #67C23A;
}

.status-icon.failed {
  color: #F56C6C;
}

.status-icon.running {
  color: #409EFF;
}

.metric-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.metric-value {
  margin-bottom: 5px;
  font-weight: 600;
}

/* 添加迷你条形图样式 */
.mini-bar-chart {
  width: 100%;
  height: 4px;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 2px;
  overflow: hidden;
}

.mini-bar {
  height: 100%;
  background-color: #409EFF;
  border-radius: 2px;
}

/* 确保el-progress组件正确显示 */
.metric-cell :deep(.el-progress) {
  width: 100%;
}

.metric-cell :deep(.el-progress-bar) {
  width: 100%;
}

.metric-cell :deep(.el-progress-bar__outer) {
  height: 4px !important;
  background-color: rgba(0, 0, 0, 0.05);
}

.metric-cell :deep(.el-progress-bar__inner) {
  transition: width 0.6s ease;
}

.time-info {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

.time-item {
  display: flex;
  align-items: center;
}

.time-item .el-icon {
  margin-right: 4px;
}

.time-separator {
  margin: 0 8px;
  color: var(--el-text-color-secondary);
}

.executor-name {
  margin-left: 8px;
  vertical-align: middle;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.running-tag {
  display: flex;
  align-items: center;
}

.running-tag .el-icon {
  margin-right: 5px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
  }
}

/* 成功率样式 */
.success-rate-high {
  color: #67C23A;
  font-weight: 600;
}

.success-rate-medium {
  color: #E6A23C;
  font-weight: 600;
}

.success-rate-low {
  color: #F56C6C;
  font-weight: 600;
}

/* 对比对话框样式 */
.comparison-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.comparison-section {
  margin-bottom: 20px;
}

.comparison-section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.comparison-section-title .el-icon {
  margin-right: 8px;
}

.task-overview-card {
  height: 100%;
}

.task-overview-card h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.task-overview-info {
  font-size: 12px;
}

.overview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.overview-label {
  color: #606266;
  font-weight: 500;
}

.overview-value {
  color: #303133;
}

/* 对比相关样式已移除 */
</style>